<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="注册"
        left-arrow
        @click-left="$router.back()"
      >
      </van-nav-bar>
    </header>
    <div class="content">
      <van-field
        v-model="telcode"
        center
        clearable
        placeholder="请输入短信验证码"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
        </template>
      </van-field>
      <van-button :disabled="flag" type="danger" block @click="nextStep">下一步</van-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { Field, Button, NavBar, Toast } from 'vant'
import { getStorage } from '@/utils/storage'
import { dosendmsgcode, docheckcode } from '@/api/user'
Vue.use(Field)
Vue.use(Button)
Vue.use(NavBar)
Vue.use(Toast)
export default {
  beforeRouteEnter (to, from, next) { // 组件内导航守卫
    const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/
    if (reg.test(getStorage('tel'))) {
      next()
    } else {
      // next('/reg_step1') XXXXXXX
      // next 默认为push
      next({
        path: '/reg_step1',
        replace: true
      })
    }
  },
  data () {
    return {
      telcode: ''
    }
  },
  methods: {
    sendCode () {
      const tel = getStorage('tel')
      dosendmsgcode({ tel }).then(res => {
        console.log(res.data)
      })
    },
    nextStep () {
      docheckcode({
        tel: getStorage('tel'),
        telcode: this.telcode
      }).then(res => {
        if (res.data.code === '10007') {
          // 验证码错误
          Toast('验证码错误')
        } else {
          this.$router.push('/reg_step3')
        }
      })
    }
  },
  computed: {
    flag () {
      return this.telcode.trim() === ''
    }
  }
}
</script>
